package com.netcracker.educenter.filestorage.beans;

import com.netcracker.educenter.filestorage.configurator.Configurator;
import com.netcracker.educenter.filestorage.datasource.dao.FileAccess;
import com.netcracker.educenter.filestorage.datasource.dao.file.FileDAO;
import com.netcracker.educenter.filestorage.datasource.entity.File;
import org.apache.log4j.Logger;

import javax.ejb.Stateless;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

@Stateless(name = "UserStatelessBean")
public class UserStatelessBean implements UserStatelessBeanLocal {

    private static final Logger log = Logger.getLogger(UserStatelessBean.class);

    @Override
    public ArrayList<File> getFiles(String userName) {

        FileAccess fileAccess = new FileDAO();
        return fileAccess.loadFileList(userName);
    }

    @Override
    public void deleteFile(String fileName, String userName) {

        // Delete information about file from database
        FileAccess fileDAO = new FileDAO();
        fileDAO.delete(fileName, userName);

        // Delete file from server
        Path filePath = Paths.get(Configurator.getConfigurator().getPath()).resolve(userName).resolve(fileName);
        try {
            Files.delete(filePath);
        } catch (IOException e) {
            log.error(String.format("Cannot delete file %s from disk. User: %s", fileName, userName), e);
        }
    }
}
